﻿using System;
using System.Linq;
using System.Threading.Tasks;
using FPP.Models;

namespace FPP.Utilities
{
    public static class Services
    {
        private static bool _isRunning = false;

        public static void CheckServicesAsync()
        {
            if (!_isRunning)
            {
                _isRunning = true;
                var t1 = new Task(CheckServices);
                t1.Start();
            }
        }

        private static void CheckServices()
        {
            var now = DateTime.Now;

            using (var context = new fppEntities(Controllers.DataAccess.ffpCString))
            {
                var needToRun = context.Services.Where(s => s.NextRun < now);
                foreach (var service in needToRun)
                {
                    switch (service.Id)
                    {
                        case 1:
                            UpdateAge();
                            break;
                        case 2:
                            NewsFeeds.CheckNewsFeeds();
                            break;
                    }
                    SetNextRun(service);
                }
                context.SaveChanges();
            }
        }

        private static void SetNextRun(Service service)
        {
            switch (service.Factor)
            {
                case "D":
                    service.NextRun = service.NextRun.AddDays(service.Frequency);
                    break;
                case "W":
                    service.NextRun = service.NextRun.AddDays(service.Frequency * 7);
                    break;
                case "H":
                    service.NextRun = service.NextRun.AddHours(service.Frequency);
                    break;
                case "M":
                    service.NextRun = service.NextRun.AddMonths(service.Frequency);
                    break;
                default:
                    service.NextRun = service.NextRun.AddDays(service.Frequency);
                    break;
            }
        }

        private static void UpdateAge()
        {
            using (var context = new fppEntities(Controllers.DataAccess.ffpCString))
            {
                var people = context.FamousPersons.ToArray();
                foreach (var person in people)
                {
                    person.UpdateAge();
                    context.ForceSave(person);
                }
            }

        }

        private static void UpdateWiki()
        {
            using (var context = new fppEntities(Controllers.DataAccess.ffpCString))
            {
                var wikiLinks = context.WikiLinks.ToArray();

                foreach (var wikiLink in wikiLinks)
                {
                }
            }
        }
    }
}